package cn.jiahua.test18;

import java.util.concurrent.RecursiveTask;

public class JoinpoinDemo  extends RecursiveTask<Long> {
    private long start;
    private long end ;


    private Long temp=10000L;   //临界值


    public JoinpoinDemo(long start, long end) {
        this.start = start;
        this.end = end;
    }

    public Long compute(){
        //是否达到临界值，达到临界值则for循环求和
        if(end-start<temp){
            long sum=0;
            for (long i=start;i<=end;i++){
                sum+=i;
            }
            return sum;
        }else{
            //大数据量  分支合并的方式的做，大任务拆份成小任务来做
             long middle=(start +end)/2;

             //forkjoin递归
            JoinpoinDemo tark1=new JoinpoinDemo(start,middle);
            tark1.fork();   //拆分任务，将任务压入线程队列中

            JoinpoinDemo tark2=new JoinpoinDemo(middle+1,end);
            tark2.fork();  //拆分任务，将任务压入线程队列中

            return tark1.join()+tark2.join();
        }
    }
}
